package com.five.calendar.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.solver.Goal;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TimeUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.five.calendar.ApplicationHelper;
import com.five.calendar.R;
import com.five.calendar.alarmmanager.clock.AlarmManagerUtil;
import com.five.calendar.common.observer.Observer;
import com.five.calendar.database.bean.TargetBean;
import com.five.calendar.database.bean.TargetDayBean;
import com.five.calendar.database.observer.TargetDayObservable;
import com.five.calendar.database.observer.TargetObservable;
import com.five.calendar.ui.calendarview.Utils;
import com.five.calendar.ui.calendarview.component.CalendarAttr;
import com.five.calendar.ui.calendarview.component.CalendarViewAdapter;
import com.five.calendar.ui.calendarview.interf.OnSelectDateListener;
import com.five.calendar.ui.calendarview.model.CalendarDate;
import com.five.calendar.ui.calendarview.view.Calendar;
import com.five.calendar.ui.calendarview.view.CustomDayView;
import com.five.calendar.ui.calendarview.view.MonthPager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zhuxiaoxinsx on 17-9-6.
 */

public class GoalDoneShowActivity extends Activity implements View.OnClickListener {
    @BindView(R.id.calendar_goal_monthpager)
    MonthPager mMonthPager;
    @BindView(R.id.back)
    ImageView mCloseIcon;
    @BindView(R.id.settings)
    ImageView mSettingsIcon;
    @BindView(R.id.complete_count)
    TextView mCompleteCountView;
    @BindView(R.id.not_yet_count)
    TextView mNotYetCountView;
    @BindView(R.id.due_time)
    TextView mDueTimeView;
    @BindView(R.id.goal_title)
    TextView mGoalTitle;
    private CalendarDate mCurrentDate;
    private OnSelectDateListener mOnSelectDateListener;
    private CalendarViewAdapter mCalendarAdapter;
    private int mCurrentPage;
    private ArrayList<Calendar> mCurrentCalendars = new ArrayList<>();
    private String[] mTimes;
    private LinearLayout mMenuView;
    private PopupWindow mPopupWindow;
    private TextView mEditItem;
    private TextView mDeleteItem;
    private TextView mGiveUpItem;
    private TextView mCompleteItem;
    private TargetBean mTargetBean;
    public static int sTextColor = 0;
    HashMap<String, String> mMarkData = new HashMap<>();
    private int mOverDueDayCount;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if(mDueTimeView != null && mTargetBean != null){
                    mDueTimeView.setText(com.five.calendar.utils.TimeUtils.timeFromCreateTime(mTargetBean.endTime));
                }
                sendEmptyMessageDelayed(1,1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goal_done_show);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        initView();
        mMonthPager.setViewheight(Utils.dpi2px(this, 270));
    }

    @Override
    protected void onResume() {
        super.onResume();
        sTextColor = 1;
        Log.e("ZXX","goaldoneShowActivity resume");
        initCurrentDate();
        initCalendarView();
    }

    private void initView() {
        mCloseIcon.setOnClickListener(this);
        mSettingsIcon.setOnClickListener(this);
    }

    private void initCalendarView() {
        initListener();
        CustomDayView customDayView = new CustomDayView(this, R.layout.calendar_done_show_custom_day);
        mCalendarAdapter = new CalendarViewAdapter(this, mOnSelectDateListener,
                CalendarAttr.CalendayType.MONTH, customDayView);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mTimes = bundle.getStringArray("times");
                mTargetBean = (TargetBean) bundle.getSerializable("targetbean");
                mGoalTitle.setText(mTargetBean.title);
                handler.sendEmptyMessage(1);
                initMarkData(mTimes);
            }
        }
        initMonthPager();
    }

    private void initMonthPager() {
        mMonthPager.setAdapter(mCalendarAdapter);
        mMonthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        mMonthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        mMonthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                mCurrentCalendars = mCalendarAdapter.getPagers();
                if (mCurrentCalendars.get(position % mCurrentCalendars.size()) instanceof Calendar) {
                    CalendarDate date = mCurrentCalendars.get(position % mCurrentCalendars.size()).getSeedDate();
                    mCurrentDate = date;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initMarkData(String[] times) {
        Log.e("ZXX", "initMarkData");
        mMarkData.put(new CalendarDate().toString(), "4");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String ymd = sf.format(mTargetBean.endTime);
        ymd = ymd + " 23:59:59";
        Log.e("ZXX", "ymd: " + ymd);
        Date date = new Date();
        String today = sf.format(date);
        today = today + " 00:00:00";
        try {
            SimpleDateFormat sfs = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date endDate = sfs.parse(ymd);
            Date todayStartDate = sfs.parse(today);
            for (long i = mTargetBean.startTime; i < endDate.getTime(); i = i + com.five.calendar.utils.TimeUtils.DAY){
                String time = com.five.calendar.utils.TimeUtils.timeFormatToCalendarDateString(i);
                Log.e("ZXX","formattime: " + time);
                //黑色字体
                mMarkData.put(time, "3");
            }
            mMarkData.put(com.five.calendar.utils.TimeUtils.timeFormatToCalendarDateString(mTargetBean.endTime), "3");
            for (long i = mTargetBean.startTime; i < todayStartDate.getTime(); i = i + com.five.calendar.utils.TimeUtils.DAY){
                String time = com.five.calendar.utils.TimeUtils.timeFormatToCalendarDateString(i);
                //到今天的全打红
                mMarkData.put(time, "5");
            }
            //打了卡的打蓝
            if (times != null) {
                mCompleteCountView.setText(times.length + "");
                for (int i = 0; i < times.length; i++) {
                    mMarkData.put(times[i], "2");
                }
            }
            //找出红色个数
            Iterator iterator = mMarkData.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                String value = (String) entry.getValue();
                if (value.equals("5")){
                    mOverDueDayCount++;
                }
            }
            mNotYetCountView.setText(mOverDueDayCount + "");
            mCalendarAdapter.setMarkData(mMarkData);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void initListener() {
        mOnSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                mMonthPager.selectOtherMonth(offset);
            }
        };
    }

    private void initCurrentDate() {
        mCurrentDate = new CalendarDate();
    }

    private void refreshClickDate(CalendarDate date) {
        mCurrentDate = date;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.settings:
                mMenuView = (LinearLayout) LayoutInflater.from(GoalDoneShowActivity.this).inflate(R.layout.settings_layout, null);
                mEditItem = (TextView) mMenuView.findViewById(R.id.edit_goal);
                mDeleteItem = (TextView) mMenuView.findViewById(R.id.detele_goal);
                mGiveUpItem = (TextView) mMenuView.findViewById(R.id.give_up_goal);
                mCompleteItem = (TextView) mMenuView.findViewById(R.id.complete_goal);
                mEditItem.setOnClickListener(this);
                mDeleteItem.setOnClickListener(this);
                mGiveUpItem.setOnClickListener(this);
                mCompleteItem.setOnClickListener(this);
                mPopupWindow = new PopupWindow(mMenuView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
                mPopupWindow.setOutsideTouchable(true);
                mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                ApplicationHelper.postRunInUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPopupWindow.showAsDropDown(findViewById(R.id.settings), -mMenuView.getWidth(), 0);
                    }
                });
                break;
            case R.id.edit_goal:
                Intent intent = new Intent(GoalDoneShowActivity.this, GoalDetailAddActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("targetbean", mTargetBean);
                intent.putExtras(bundle);
                startActivity(intent);
                mPopupWindow.dismiss();
                break;
            case R.id.detele_goal:
                ArrayList<TargetBean> targetBeans = new ArrayList<>();
                targetBeans.add(mTargetBean);
                TargetObservable.deleteTarget(targetBeans).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                    @Override
                    public void onFail(Integer integer) {

                    }

                    @Override
                    public void onComplete(List<TargetBean> targetBeen) {
                        AlarmManagerUtil.cancelAlarm(GoalDoneShowActivity.this, AlarmManagerUtil.ALARM_ACTION, (int)mTargetBean.id + 1000);
                        finish();
                    }

                    @Override
                    public void onSuccess(TargetBean targetBean) {

                    }
                }).startDataHandle();
                TargetDayObservable.queryTargetByTargetId(mTargetBean.id).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                    @Override
                    public void onFail(Integer integer) {

                    }

                    @Override
                    public void onComplete(List<TargetDayBean> targetDayBeen) {
                        TargetDayObservable.deleteTarget(targetDayBeen).startDataHandle();
                    }

                    @Override
                    public void onSuccess(TargetDayBean targetDayBean) {

                    }
                }).startDataHandle();
                mPopupWindow.dismiss();
                break;
            case R.id.give_up_goal:
                mTargetBean.isComplete = 2;
                TargetObservable.updateTarget(mTargetBean).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                    @Override
                    public void onFail(Integer integer) {

                    }

                    @Override
                    public void onComplete(List<TargetBean> targetBeans) {

                    }

                    @Override
                    public void onSuccess(TargetBean targetBean) {
                        Toast.makeText(GoalDoneShowActivity.this, "success update", Toast.LENGTH_SHORT).show();
                        AlarmManagerUtil.cancelAlarm(GoalDoneShowActivity.this, AlarmManagerUtil.ALARM_ACTION, (int)mTargetBean.id + 1000);
                        finish();
                    }
                }).startDataHandle();
                break;
            case R.id.complete_goal:
                mTargetBean.isComplete = 1;
                TargetObservable.updateTarget(mTargetBean).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                    @Override
                    public void onFail(Integer integer) {

                    }

                    @Override
                    public void onComplete(List<TargetBean> targetBeans) {

                    }

                    @Override
                    public void onSuccess(TargetBean targetBean) {
                        Toast.makeText(GoalDoneShowActivity.this, "success update", Toast.LENGTH_SHORT).show();
                        AlarmManagerUtil.cancelAlarm(GoalDoneShowActivity.this, AlarmManagerUtil.ALARM_ACTION, (int)mTargetBean.id + 1000);
                        finish();
                    }
                }).startDataHandle();
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        sTextColor = 0;
    }
}
